<?php
namespace app\index\controller;

use think\Controller;
use think\Request;
use think\Session;
use think\Cookie;

//代理查询

class Query extends Controller{
	
	//查询
    public function index(){
		
		$request = Request::instance();
		
		if(!IS_TEST){
		
			//当前登陆状态
			if(!Session::has('wechat_id')){
				$this->wxlogin();
				exit();
			}
		}else{
			//测试
			Session::set('wechat_id','abc');
		}

		//显示页面
		defined('WECHAT_ID') or define('WECHAT_ID',Session::get('wechat_id'));

		return view('');
    }
	
	//代理查询结果
	public function agent(){
		if(!Session::has('wechat_id')){
			$this->redirect('Query/index'); exit();
		}
		$pm = [
			'phonenum' => Request::instance()->param('tel')
		];
		
		if(!preg_match('/^1\d{10}$/',$pm['phonenum'])){
			$this->error('请输入正确的手机号码');
		}
		$res = \ServerHelper::post('query_agent',$pm);
		$data = $this->J($res);

		if(empty($data['flag'])){
			$this->error($data['msg']);
		}
		
		$data['data']['template_value']['id_card'][1] = substr_replace($data['data']['template_value']['id_card'][1],'****************',1,16);
		
		if(Cookie::has('certificate' . $pm['phonenum'])){
			
			$data['data']['new_image'] = Cookie::get('certificate' . $pm['phonenum']);
			
		}else{
			//处理图片
			Vendor('CreateCertificate.CreateCertificate');
			$hp = new \CreateCertificate();
			list($flag,$info,$localpath) = $hp->create($data['data']['template_pic'],$data['data']);

			//上传到OSS
			$remotePath = 'uploads/' . date('Ym') . '/' . uniqid() .  '.png';
			$res = \ServerHelper::GetOSSConfig();
			$hp = new \AliyunOSSHelper($res);
			$result = $hp->uploadLocal($localpath,$remotePath,true);
			
			$data['data']['new_image'] = $result['data'];
			
			//缓存一些时间
			Cookie::set('certificate' . $pm['phonenum'],$result['data'],180);
		}
		
		//发送查询结果
		$result = [
			'wechatid' => Session::get('wechat_id'),
			'phonenum' => $pm['phonenum'],
			'queryimage' => $data['data']['new_image']
		];
		\ServerHelper::post('query_result_notify',$result);
		
		return view('',$data['data']);
	}
	
	private function J($list){
		$data = json_decode($list,true);
		if(!isset($data['flag'])){
			__log($list,'welogin');
			if(Request::instance()->isAjax()){
				ajax('网络错误');
			}
			exit('net error');
		}
		return $data;
	}
	
	private function wxlogin(){
		
		if(!__iswechat()){
			$this->error('请在微信中登陆');
		}
		
		$cfg = \ServerHelper::GetWeChatConfig();
		if(!isset($cfg['appid'])){
			__log('登录：没有设置微信appid','weixin');
			$this->error('系统错误');
			exit();
		}
		
		$appid = $cfg['appid'];
		
		$request = Request::instance();
		
		$redirect_uri = urlencode($request->domain() . url('Query/wechat_redirect'));
		$url = "https://open.weixin.qq.com/connect/oauth2/authorize";
		$url.="?appid=$appid&redirect_uri=$redirect_uri&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect";
		
		$this->redirect($url);
	}
	
	public function wechat_redirect(){
		//载入配置信息
		$cfg = \ServerHelper::GetWeChatConfig();
		if(
			!isset($cfg['appid']) || 
			!isset($cfg['appsecret'])
			){
			__log('登录：没有设置微信appid或appsecret','weixin');
			$this->error('系统错误');
			exit();
		}
		$appid = $cfg['appid'];
		$appsecret = $cfg['appsecret'];
		
		//拉取请求
		$request = Request::instance();

		//第一步返回的 得到了 Code
		$code = $request->param('code','');
		if($code == ''){
			$this->error('登录发起失败');
		}

		//第二步：通过code换取网页授权access_token
		$url ="https://api.weixin.qq.com/sns/oauth2/access_token";
		$url.="?appid=$appid&secret=$appsecret&code=$code&grant_type=authorization_code";
		$info = $this->getJson($url);
		if(!isset($info['refresh_token'])){
			$this->error('登陆发起失败');
		}

		//第三步：刷新access_token（如果需要）
		$refresh_token = $info['refresh_token'];
		$url = "https://api.weixin.qq.com/sns/oauth2/refresh_token";
		$url.= "?appid=$appid&grant_type=refresh_token&refresh_token=$refresh_token";
		$info = $this->getJson($url);
		if(
			!isset($info['access_token']) || 
			!isset($info['openid'])
		){
			$this->error('登陆发起失败');
		}
		
		Session::set('wechat_id',$info['openid']);

		$this->redirect('Query/index');

	}
	
	private function getJson($url){
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL, $url);
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); 
		curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE); 
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		$output = curl_exec($ch);
		curl_close($ch);
		return json_decode($output, true);
	}
	
	//授权证书
	public function certificate(){
		return view();
	}
	
	public function clearcache(){
		Session::clear();
        echo 'success';
    }
	
	
}
